<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 360px;" v-model="find_data.find" placeholder="请输入站点名称或备注" clearable
                        prefix-icon="Search" />
                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;">
                    <el-button @click="add_btn" type="primary" icon="SuccessFilled">添加</el-button>
                    <el-button @click="up_btn" type="warning" icon="WarnTriangleFilled">修改</el-button>
                    <el-button @click="del_btn" type="danger" icon="CircleCloseFilled">删除</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%">
                    <el-table-column type="selection" width="35" />
                    <el-table-column label="编号" width="55" fixed type="index" />

                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'belongProvince'" #="{ row, column, $index }">
                                <span>{{ row.belongProvince + '-' + row.belongCity + '-' + row.belongCounty }}</span>

                            </template>
                        </el-table-column>
                    </template>
                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true"
                    layout="prev, pager, next, jumper,->,sizes,total," :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:75px;z-index: 2;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="110px" label-suffix="：">
                <el-form-item label="酒店名称" :required="false">
                    <el-input v-model="add_data.stationName" placeholder="请输入酒店名称" />
                </el-form-item>
                <el-form-item label="酒店地址" :required="false">
                    <el-input @click="map_off_btn" v-model="add_data.address" placeholder="请选择酒店地址" />
                </el-form-item>
                <el-form-item label="酒店电话" :required="false">
                    <el-input type="number" v-model="add_data.hotelLinkPhone" placeholder="请输入酒店电话" />
                </el-form-item>
                <!-- <el-form-item label="酒店备注" :required="false">
                    <el-input show-word-limit maxlength="30" type="textarea" placeholder="请选择酒店备注"
                        v-model="add_data.nameNote" />
                </el-form-item> -->
                <el-form-item label="酒店简称" :required="false">
                    <el-input style="width: 160px;" v-model="add_nameNote" placeholder="请输入酒店简称" />
                    <el-button style="margin-left:20px" @click="add_nameNote_btn" type="primary"
                        icon="Plus">添加</el-button>
                </el-form-item>
                <div v-if="add_nameNote_list.length > 0">
                    <el-tag style="margin-left:10px;margin-top:5px" v-for="item in add_nameNote_list"
                        :key="item.customers" class="mx-1" closable type="danger" @close="close_btn(item)">
                        {{ item }}
                    </el-tag>
                </div>
            </el-form>

            <el-button @click="ok_btn" style="margin-left:30vw;margin-top:5px" type="primary">确认提交</el-button>
        </el-dialog>
        <!-- 地图弹窗 -->
        <el-dialog style="margin-top:10vh;height:80vh;overflow: hidden;" v-model="map_off" title="酒店地址:" width="80%"
            :close-on-click-modal='false'>
            <div id="myMap" style="height: 65vh; width: 100%">
                <div class="map_input">
                    <el-input @input="map_change" id='tipinput' style="width:40%" v-model="map_address"
                        placeholder="请输入酒店地址">
                        <template #prepend>酒店地址:</template>
                    </el-input>
                    <el-button @click="map_ok_btn" type="primary">确认</el-button>
                </div>
                <div v-if="map_address_list.length > 0" class="map_input">
                    <div style="width:40%;background:#fff;margin-left:20px;padding: 10px;font-weight: 700;">
                        <div @click="map_list_btn(item)" class="div_bg" v-for="(item, index) in map_address_list"
                            :key="index" style="margin-top: 10px;">
                            {{ item.district }}-{{ item.address }}-{{ item.name }}
                        </div>
                    </div>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import CircularJSON from 'circular-json'
import { ref, reactive, onMounted, computed } from 'vue'
import { getStationListPages, adupStationList, delStationList, getStationType, adupPrivateSet, getPrivateSetList } from '@/api/customer_list.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import AMapLoader from "@amap/amap-jsapi-loader"
import { securityJsCode, key } from '@/utils/common.js'
onMounted(async () => {
    let hotel = JSON.parse(localStorage.getItem('hotel'))
    if (hotel) {
        find_data.find = hotel.find

    }
    getStationType({}).then(res => {
        console.log(res)
    })

    getPrivateSetList({
        find: '地点设置',
        page: {
            pageNum: 1,
            pageSize: 999,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            table_data_list_new.value = table_data_list
        }
    })


    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

            // 重新赋值给列数组
            // let cols = that.U.scopy(that.fields);
            // let list = cols.filter(it => { return it.show; });
            // that.$emit('saveSet', {dgName: that.dgName, cols: list});
        }
    })

    await list_api()
})

//#region 表格数据处理
const table_data_list = reactive([
    { label: '地址简称', field: 'stationName', width: '', off: true },
    { label: '省份', field: 'belongProvince', width: 200, off: true },
    { label: '详细地址', field: 'address', width: '', off: true },
    { label: '经纬度', field: 'lngLat', width: 180, off: true },
    { label: '操作人', field: 'userId', width: 130, off: true },
    { label: '酒店电话', field: 'hotelLinkPhone', width: 180, off: true },
    { label: '备注', field: 'nameNote', width: 200, off: true },
    { label: '添加时间', field: 'addTime', width: 165, off: true },
])

const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '地点设置',
        tbNum: "hotel",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion



//#region 地图
const myMap = ref('')
const geolocation = ref('') // 定位
const map_address = ref('')
const map_address_list = ref([])
const map_value = ref({})
const marker = ref('')
const map_off = ref(false)
const map_off_btn = () => {
    map_off.value = true
    // 地图
    window._AMapSecurityConfig = {
        securityJsCode: securityJsCode,
    }
    // 首次加载
    AMapLoader.load({
        key: key,
        version: '2.0',
        plugins: ['AMap.Driving', 'AMap.Geolocation', 'AMap.Scale', 'AMap.AutoComplete', 'AMap.PlaceSearch'],
    }).then((AMap) => {
        // 初始化-地图对象
        myMap.value = new AMap.Map('myMap', { zoom: 10, center: [104.065861, 30.657401] });
        myMap.value.addControl(new AMap.Scale())
        geolocation.value = new AMap.Geolocation({ //定位
            enableHighAccuracy: true, //是否使用高精度定位，默认:true
            convert: true, //自动偏移坐标 为高德坐标，默认：true
            timeout: 5000, //超过5秒后停止定位，默认：无穷大
            buttonPosition: 'RB', //定位按钮停靠位置
            showMarker: true, //定位成功在位置显示点标记，默认：true
        })
        myMap.value.addControl(geolocation.value)
        geolocation.value.getCurrentPosition((status, result) => {
            console.log('定位getCurrentPosition', status, result);
            if (status == 'complete') {
                console.log('定位信息', result);
            } else {
                console.log('定位出错', result);
            }
        })



    }).catch(err => { console.log('高德地图加载失败：', err); });
}
const map_change = () => {
    let autoOptions = {
        city: '成都市'
    }
    var autoComplete = new AMap.Autocomplete(autoOptions);
    autoComplete.search(map_address.value, function (status, result) {
        // 搜索成功时，result即是对应的匹配数据
        map_address_list.value = result.tips.slice(0, 5)
    })
}




const map_list_btn = (e) => {
    console.log(e)
    map_address.value = e.district + '-' + e.address + '-' + e.name
    map_value.value = e

    myMap.value.panTo([e.location.lng, e.location.lat]);
    if (marker.value) {
        myMap.value.remove(marker.value);
    }
    myMap.value.setFitView();
    marker.value = new AMap.Marker({
        map: myMap.value,
        position: [e.location.lng, e.location.lat],
    });
    myMap.value.setFitView();
    console.log(myMap.value)
    myMap.value.add(marker.value);


}
const map_ok_btn = () => {



    // 提取省份
    let province = map_value.value.district.match(/([\u4E00-\u9FA5]{2,3})(省|自治区|特别行政区)/);
    console.log(province[0]); // 四川省

    // 提取城市
    let city = map_value.value.district.match(/([\u4E00-\u9FA5]{2,3})(市|县|区)/);
    console.log(city[0].substring(1)); // 成都市

    // 提取区县
    let district = map_value.value.district.match(/([\u4E00-\u9FA5]{2,3}(区|县))/);
    console.log(district[0].substring(1)); // 金牛区

    add_data.address = map_value.value.district + map_value.value.address + map_value.value.name
    add_data.belongCity = city[0].substring(1)
    add_data.belongCounty = district[0].substring(1)
    add_data.belongProvince = province[0]
    add_data.lat = map_value.value.location.lat
    add_data.lng = map_value.value.location.lng
    map_off.value = false

}
//#endregion
//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    find: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getStationListPages(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total
    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('添加价格模版设置')
const add_data = reactive({
    address: '',
    belongCity: '',
    belongCounty: '',
    belongProvince: "",
    id: "",
    lat: '',
    lng: "",
    nameNote: "",
    stationName: '',
    stationType: 'HOTEL',
    hotelLinkPhone: ''
})

const add_btn = () => {

    title.value = '添加酒店设置'
    add_data.address = ''
    add_data.belongCity = ''
    add_data.belongCounty = ''
    add_data.belongProvince = ''
    add_data.id = ''
    add_data.lat = ''
    add_data.lng = ''
    add_data.nameNote = ''
    add_data.stationName = ''
    add_data.hotelLinkPhone = ''
    add_data.stationType = 'HOTEL'
    add_off.value = true

}
// 酒店简称
const add_nameNote = ref('')
const add_nameNote_list = ref([])
const add_nameNote_btn = () => {
    console.log(add_nameNote.value)
    if (!add_nameNote.value) {
        return ElMessage({
            message: '请输入酒店简称！',
            type: 'warning',
        })
    }
    add_nameNote_list.value.push(add_nameNote.value)
    add_nameNote.value = ''
    add_data.nameNote = add_nameNote_list.value.join(',')
    console.log(add_data.nameNote)

}

//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }


    title.value = '修改酒店设置'
    add_data.hotelLinkPhone = table_list.value[0].hotelLinkPhone
    add_data.address = table_list.value[0].address
    add_data.belongCity = table_list.value[0].belongCity
    add_data.belongCounty = table_list.value[0].belongCounty
    add_data.belongProvince = table_list.value[0].belongProvince
    add_data.lat = table_list.value[0].lat
    add_data.lng = table_list.value[0].lng
    add_data.nameNote = table_list.value[0].nameNote
    add_nameNote_list.value = table_list.value[0].nameNote.split(',');
    add_data.stationName = table_list.value[0].stationName
    add_data.stationType = table_list.value[0].stationType
    add_data.id = table_list.value[0].id
    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {

    if (!add_data.address) {
        return ElMessage({
            message: '请选择酒店位置',
            type: 'warning',
        })
    } else if (!add_data.stationName) {
        return ElMessage({
            message: '请输入酒店名称',
            type: 'warning',
        })
    } else if (!add_data.nameNote) {
        if (!add_nameNote.value) {
            return ElMessage({
                message: '请输入酒店名称',
                type: 'warning',
            })
        }
    }


    if (title.value == '添加酒店设置') {

        let ps = {
            hotelLinkPhone: add_data.hotelLinkPhone,
            address: add_data.address,
            belongCity: add_data.belongCity,
            belongCounty: add_data.belongCounty,
            belongProvince: add_data.belongProvince,
            lat: add_data.lat,
            lng: add_data.lng,
            nameNote: add_data.nameNote ? add_data.nameNote : add_nameNote.value,
            stationName: add_data.stationName,
            stationType: add_data.stationType,
        }

        adupStationList(ps).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {
        let ps = {
            hotelLinkPhone: add_data.hotelLinkPhone,
            address: add_data.address,
            belongCity: add_data.belongCity,
            belongCounty: add_data.belongCounty,
            belongProvince: add_data.belongProvince,
            lat: add_data.lat,
            lng: add_data.lng,
            nameNote: add_data.nameNote ? add_data.nameNote : add_nameNote.value,
            stationName: add_data.stationName,
            stationType: add_data.stationType,
            id: add_data.id
        }

        adupStationList(ps).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    ElMessageBox.confirm(
        '是否确认删除客户?',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delStationList({
                ids: [table_list.value[0].id]
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
    localStorage.setItem('hotel', CircularJSON.stringify(find_data))
    list_api()
}
//#endregion
</script>

<style scoped lang='scss'>
.map_input {
    width: 100%;
    position: relative;
    z-index: 1;
    display: flex;
    justify-content: center;

}

.div_bg:hover {
    background-color: darkgray;
}
</style>
<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}

.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
